# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/5/7 14:39
# @Author  : qiaoc
# @File    : AuditRuleEle.py
# @Desc    : 【缴费单】 - 稽核规则

from affix import AffixUtils
import pandas as pandas
from ocr.Ocr import *
import datetime

# 不用处理的标杆类型
no_need_to_deal_with_benchmark_type = ['智能电表标杆（动环）', '智能电表标杆（集采）', '动环负载标杆', '平峰谷均价标杆（录平峰谷表采用总量录入方式时）']



"""
    稽核规则十一：【页面稽核】
        1.增加“平均电费单价”展示，计算公式为：平均电费单价=【实际报账金额】/【实际总耗电量】，如此值小于等于0.3或者大于等于0.7，转人工稽核。
                其他稽核条件均需识别判断展示。
        2.备注：均电费单价小于等于0.3/大于等于0.7
"""
def audit_rule_eleven(auditResult, audit_list, bill_number, result,
                      payment_electric_info_actual_reimbursement_amount, rp_payment_info_actual_total_pc):
    """
    :param payment_electric_info_actual_reimbursement_amount: 实际报账金额
    :param rp_payment_info_actual_total_pc: 实际总耗电量
    :return:
    """
    try:
        if payment_electric_info_actual_reimbursement_amount and rp_payment_info_actual_total_pc:
            if float(rp_payment_info_actual_total_pc) != 0:
                average_unit_price_of_electricity = round(
                    float(payment_electric_info_actual_reimbursement_amount) / float(
                        rp_payment_info_actual_total_pc), 2)
                if average_unit_price_of_electricity <= 0.3 or average_unit_price_of_electricity >= 0.7:
                    auditResult.auditStatus = '审核中'  # 返回稽核结果为转人工
                    result['message'] = '均电费单价小于等于0.3/大于等于0.7'
                    audit_list.append([str(bill_number), '平均电费单价',
                                       str(average_unit_price_of_electricity),
                                       '小于等于0.3/大于等于0.7', '0', 'RPA', '平均电费单价小于等于0.3/大于等于0.7', '', '1', ''])
                else:
                    audit_list.append([str(bill_number), '平均电费单价',
                                       str(average_unit_price_of_electricity),
                                       '小于等于0.3/大于等于0.7', '1', 'RPA', '合格', '', '1', ''])
            else:
                auditResult.auditStatus = '审核中'  # 返回稽核结果为转人工
                result['message'] = '平均电费单价小于等于0.3/大于等于0.7'
                audit_list.append([str(bill_number), '平均电费单价',
                                   '0',
                                   '小于等于0.3/大于等于0.7', '0', 'RPA', '平均电费单价小于等于0.3/大于等于0.7', '', '1', ''])
        else:
            auditResult.auditStatus = '审核中'  # 转人工
            audit_list.append(
                [str(bill_number), '平均电费单价', '', '小于等于0.3/大于等于0.7', '0', 'RPA', '实际报账金额或实际总耗电量为空', '',
                 '1', ''])
    except Exception as e:
        # print(e)
        auditResult.auditStatus = '审核中'  # 转人工
        audit_list.append(
            [str(bill_number), '平均电费单价', '', '小于等于0.3/大于等于0.7', '0', 'RPA', 'RPA处理异常', '', '1', ''])

    return audit_list, auditResult

"""
    稽核规则二：【页面稽核】
        页面【报账点缴费信息】-【实际不含税电费金额】+【实际电费税金】+【其他费用】的【含税金额】=【实际报账金额】
            # ----  不一致后动作：【审核状态】-【不通过】，备注：【实际不含税电费金额】+【实际电费税金】+【其他费用】的【含税金额】不等于【实际报账金额】
"""
def audit_rule_two(auditResult, audit_list, audit_refused_type, bill_number,
                   payment_electric_info_actual_reimbursement_amount,
                   actual_nae_taxsad, actual_ef_tariff, actual_reimbursement_amount):
    """
    :param payment_electric_info_actual_reimbursement_amount: 实际报账金额
    :param actual_nae_taxsad:  实际不含税电费金额
    :param actual_ef_tariff: 【其他费用】的【含税金额】
    :param actual_reimbursement_amount: 实际不含税电费金额
    :return:
    """
    try:
        if round(float(actual_nae_taxsad) + float(actual_ef_tariff) + float(actual_reimbursement_amount),
                 2) != float(payment_electric_info_actual_reimbursement_amount):
            auditResult.auditStatus = '不通过'  # 返回稽核结果为不通过
            audit_refused_type['金额有误'] = 0
            audit_list.append([str(bill_number), '总金额（其他费用）', str(round(
                float(actual_nae_taxsad) + float(actual_ef_tariff) + float(actual_reimbursement_amount), 2)),
                               str(payment_electric_info_actual_reimbursement_amount), '0', 'RPA',
                               '【实际不含税电费金额】+【实际电费税金】+【其他费用】的【含税金额】不等于【实际报账金额】', '', '1', ''])
        else:
            audit_list.append([str(bill_number), '总金额（其他费用）',
                               str(round(float(actual_nae_taxsad) + float(actual_ef_tariff) + float(
                                   actual_reimbursement_amount), 2)),
                               str(payment_electric_info_actual_reimbursement_amount), '1', 'RPA', '合格', '',
                               '1', ''])
    except Exception as e:
        auditResult.auditStatus = '审核中'
        audit_list.append([str(bill_number), '总金额（其他费用）',
                           str(actual_nae_taxsad) + '+' + str(actual_ef_tariff) + '+' + str(
                               actual_reimbursement_amount),
                           str(payment_electric_info_actual_reimbursement_amount), '0', 'RPA',
                           '【实际不含税电费金额】+【实际电费税金】+【其他费用】的【含税金额】不等于【实际报账金额】', '', '1', ''])
    return audit_list, auditResult,audit_refused_type

"""
    稽核规则十二：【页面稽核】
        增加“电损电量占比”展示，计算公式为：电损电量占比=【电损电量(度)】/【分摊后度数(度)】，如此值大于等于10%，转人工稽核。其他稽核条件均需识别判断展示。
            #          备注：电损电量占比大于等于10%

"""
def audit_rule_twelve(auditResult, audit_list, bill_number, whether_execute,
                      payment_detail_info_data, electricity_loss, share_degrees):
    """
    :param whether_execute: 是否为单块电表
    :param payment_detail_info_data: 电表数据
    :param electricity_loss: 【电损电量(度)】
    :param share_degrees:【分摊后度数(度)】
    :return:
    """
    if whether_execute == False:  # 单个电表
        try:
            if electricity_loss and share_degrees:
                proportion_of_power_loss_list = []
                if float(share_degrees) != 0:
                    select_data_list = PyMysql().select_eleinfo('payment_detail_info', 'payment_code', bill_number)
                    if str(electricity_loss) != '0':
                        for num, select_data in enumerate(select_data_list[2]):
                            if num >= 1 and float(select_data) == 0:
                                continue
                            proportion_of_power_loss = round(float(select_data) / float(share_degrees), 2)
                            proportion_of_power_loss_list.append(proportion_of_power_loss)
                    else:
                        proportion_of_power_loss = round(float(electricity_loss) / float(share_degrees), 2)
                        proportion_of_power_loss_list.append(proportion_of_power_loss)
                    for proportion_of_power_loss in proportion_of_power_loss_list:
                        if proportion_of_power_loss >= 0.1:
                            auditResult.auditStatus = '审核中'  # 返回稽核结果为转人工
                            audit_list.append(
                                [str(bill_number), '电损电量占比', str(proportion_of_power_loss),
                                 str(proportion_of_power_loss),
                                 '0', 'RPA', '电损电量占比大于等于10%', '', '1', ''])
                        else:
                            audit_list.append(
                                [str(bill_number), '电损电量占比', str(proportion_of_power_loss),
                                 str(proportion_of_power_loss),
                                 '1', 'RPA', '合格', '', '1', ''])
                else:
                    auditResult.auditStatus = '审核中'  # 返回稽核结果为转人工
                    audit_list.append(
                        [str(bill_number), '电损电量占比', '0',
                         '0',
                         '0', 'RPA', '电损电量占比大于等于10%', '', '1', ''])
            else:
                if str(electricity_loss) == '0':
                    audit_list.append(
                        [str(bill_number), '电损电量占比', str(electricity_loss), str(electricity_loss), '1', 'RPA', '合格', '',
                         '1', ''])
                else:
                    auditResult.auditStatus = '审核中'  # 转人工
                    audit_list.append([str(bill_number), '电损电量占比', '', '', '0', 'RPA', '电损电量或分摊后度数为空', '', '1', ''])
        except Exception as e:
            # print(e)
            auditResult.auditStatus = '审核中'  # 转人工
            audit_list.append([str(bill_number), '电损电量占比', '', '', '0', 'RPA', 'RPA处理异常', '', '1', ''])
    else:  # 多个电表
        sum_select_data = 0.00
        sum_share_degrees = 0.00
        sum_electricity_loss = 0.00
        try:
            for data in payment_detail_info_data:
                electricity_loss = data['electricity_loss']
                share_degrees = data['share_degrees']  # 【分摊后度数(度)】

                if electricity_loss and share_degrees:
                    select_data_list = PyMysql().select_eleinfo1(data)

                    if str(electricity_loss) != '0':
                        for num, select_data in enumerate(select_data_list[2]):
                            if num >= 1 and float(select_data) == 0:
                                continue
                            sum_select_data += select_data
                            sum_share_degrees += share_degrees
                    else:
                        sum_electricity_loss += electricity_loss

                else:
                    if electricity_loss == '0':
                        audit_list.append(
                            [str(bill_number), '电损电量占比', '(' + str(data['es_number']) + ')' + str(electricity_loss),
                             str(electricity_loss), '1', 'RPA', '合格', '', '1', ''])
                    else:
                        auditResult.auditStatus = '审核中'  # 转人工
                        audit_list.append(
                            [str(bill_number), '电损电量占比', '(' + str(data['es_number']) + ')', '', '0', 'RPA',
                             '电损电量或分摊后度数为空', '', '1', ''])

                # 每块电表相加之和判断  2021-07
                if sum_electricity_loss != 0.00:
                    proportion_of_power_loss = round(float(sum_select_data) / float(sum_share_degrees), 2)
                else:
                    proportion_of_power_loss = round(float(sum_electricity_loss) / float(sum_share_degrees), 2)

                if sum(proportion_of_power_loss) >= 0.1:
                    auditResult.auditStatus = '审核中'  # 返回稽核结果为转人工
                    audit_list.append(
                        [str(bill_number), '电损电量占比',
                         '(' + str(data['es_number']) + ')' + str(proportion_of_power_loss),
                         str(proportion_of_power_loss),
                         '0', 'RPA', '电损电量占比大于等于10%', '', '1', ''])
                else:
                    audit_list.append(
                        [str(bill_number), '电损电量占比',
                         '(' + str(data['es_number']) + ')' + str(proportion_of_power_loss),
                         str(proportion_of_power_loss),
                         '1', 'RPA', '合格', '', '1', ''])
        except Exception as e:
            # print(e)
            auditResult.auditStatus = '审核中'  # 转人工
            audit_list.append(
                [str(bill_number), '电损电量占比', '(' + str(data['es_number']) + ')', '', '0', 'RPA', 'RPA处理异常', '', '1',
                 ''])
    return audit_list, auditResult

"""
    稽核规则四：【页面稽核】
        页面【缴费标杆信息】-【标杆类型】（七类）-其中一类高于阈值（后期配置）为异常。目前为五类，预留两类，分别为智能电表标杆和动环负载标杆。
            # ----   先判断“是否超标（超标类型）”内容是否是“高于上限”，是则继续，“额定功率标杆”类型则判断超标率是否大于0%，其他类型则判断超标率是否大于20%
            # ----   异常后动作：检查是否存在附件5；如果附件5为单站，直接跳过（只需判断是否存在附件5）；如果附件5为汇总，进入附件6（excel）查找是否该户号；
            # ----             如果附件存在转人工（把所有的核对点都做了），如果附件不存在：【审核状态】-【不通过】，备注：请上传超标情况分析报告
"""
def audit_rule_four(auditResult, audit_list, bill_number, audit_refused_type,
                    payment_benchmark_info_data, all_file, affix_list_from_db, floder_path, es_number):
    """
    :param payment_benchmark_info_data: 缴费标杆信息
    :param all_file: 附件信息
    :param affix_list_from_db:
    :param floder_path: 路径
    :param es_number: 电表户号
    :return:
    """


    exceeding_rate_error_flag = False  # 默认超标率阀值
    exceeding_rate_message = ''
    exceeding_rate_error_message = ''
    if payment_benchmark_info_data and len(payment_benchmark_info_data) > 0:
        for pbid in payment_benchmark_info_data:
            is_exceeding = pbid['is_exceeding']  # 是否超标（超标类型）
            benchmark_type_name = pbid['benchmark_type_name']  # 标杆类型名称
            # 属于四种预留类型的标杆时，跳过不处理
            if benchmark_type_name in no_need_to_deal_with_benchmark_type:
                continue
            exceeding_rate_message = exceeding_rate_message + ',' + benchmark_type_name + ':' + str(
                pbid['exceeding_rate'])
            if '高于上限' in str(is_exceeding):
                exceeding_rate = str(pbid['exceeding_rate']).replace('%', '').replace('-', '0').replace(",", '')  # 超标率
                # if '额定功率标杆' in str(benchmark_type_name):
                #     exceeding_rate_default = 0
                # else:
                #     exceeding_rate_default = 20
                exceeding_rate_default = 0  # 修改为高于上限0 2021-07
                if float(exceeding_rate) > exceeding_rate_default:
                    exceeding_rate_error_flag = True
                    exceeding_rate_error_message = exceeding_rate_error_message + ',' + benchmark_type_name + ':' + str(
                        pbid['exceeding_rate'])
        if exceeding_rate_error_flag:
            att_4_name = ''
            try:
                att_4_name = all_file['附件5']
                auditResult.auditStatus = '审核中'  # 返回稽核结果为转人工
                if '单站' in str(att_4_name):
                    audit_list.append(
                        [str(bill_number), '超标说明', '超标', '有附件', '1', 'RPA', '合格',
                         AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件5'), '3', ''])
                elif '汇总' in str(att_4_name):
                    att_5_name = all_file['附件6']
                    if att_5_name == '':
                        auditResult.auditStatus = '不通过'  # 返回稽核结果为不通过
                        audit_refused_type['超标杆未分析或分析不合理'] = 0
                        audit_list.append(
                            [str(bill_number), '超标说明', '超标', '无附件', '0', 'RPA', '请上传异常情况分析汇总表',
                             AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件6'), '3', ''])
                    else:
                        # todo: 解析附件6中的excel，可能是压缩包，查找户号，找到则转人工，
                        exe_data = pandas.read_excel(floder_path + '//附件6//' + att_5_name)
                        num_list = []
                        auditResult.auditStatus = '审核中'
                        try:
                            try:
                                exe_data = pandas.read_excel(floder_path + '//附件6//' + att_5_name, header=1)
                                num_list = exe_data.loc[:, ['户号']].dropna().values.tolist()
                            except:
                                exe_data = pandas.read_excel(floder_path + '//附件6//' + att_5_name)
                                num_list = exe_data.loc[:, ['户号']].dropna().values.tolist()
                            num_flag = False
                            for num in num_list:
                                if str(num[0]).replace('.0', '') in es_number or es_number in str(num[0]).replace('.0',
                                                                                                                  ''):
                                    num_flag = True
                                    break
                            if num_flag:
                                audit_list.append(
                                    [str(bill_number), '超标说明', '超标', '有附件', '1', 'RPA', '合格',
                                     AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件6'), '3', ''])
                            else:
                                auditResult.auditStatus = '不通过'  # 返回稽核结果为不通过
                                audit_refused_type['超标杆未分析或分析不合理'] = 0
                                audit_list.append(
                                    [str(bill_number), '超标说明', '超标', '无附件', '0', 'RPA', '请上传异常情况分析汇总表',
                                     AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件5'), '3', ''])
                        except:
                            auditResult.auditStatus = '不通过'  # 返回稽核结果为不通过
                            audit_refused_type['超标杆未分析或分析不合理'] = 0
                            audit_list.append(
                                [str(bill_number), '超标说明', '超标', '有附件', '0', 'RPA', '超标明细找不到【户名】列',
                                 AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件6'), '3', ''])

                else:
                    auditResult.auditStatus = '不通过'  # 返回稽核结果为不通过
                    audit_refused_type['超标杆未分析或分析不合理'] = 0
                    audit_list.append(
                        [str(bill_number), '超标说明', '超标', '无附件', '0', 'RPA', '请上传异常情况分析汇总表',
                         AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件5'), '3', ''])

            except Exception as e:
                # print(e, ' ', e.__traceback__.tb_lineno)
                audit_list.append(
                    [str(bill_number), '超标说明', '超标', '无附件', '0', 'RPA执行异常', '请上传超标情况分析报告',
                     AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件5'), '3',
                     ''])

        else:
            att_4_name = all_file['附件5']
            if att_4_name:
                audit_list.append(
                    [str(bill_number), '超标说明', '不超标', '有附件', '1', 'RPA', '合格',
                     AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件5'), '3', ''])
            else:
                audit_list.append(
                    [str(bill_number), '超标说明', '不超标', '无附件', '1', 'RPA', '合格',
                     AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件5'), '3', ''])
    return audit_list, auditResult ,audit_refused_type

"""
    稽核规则一：【数据稽核】
        页面【电表缴费明细信息】-【电表户号】查找附件二【用户编号】的【客户地址】与对应的页面【报账点名称】作匹对
                # ----   不一致：报账点名称与电力清单中名称不一致
"""
def audit_rule_one(audit_list, rar_file, bill_number,
                   affix_list_from_db, bill_table_uname, file_flag2, rp_name):
    """
    :param rar_file: 文件格式不正确的信息
    :param affix_list_from_db:
    :param bill_table_uname: 【附件识别表】-报账点名称
    :param file_flag2: 附件2是否存在
    :param rp_name: 报账点名称
    :return:
    """
    if '附件2' in rar_file:
        audit_list.append(
            [str(bill_number), '报账点名称', str(rp_name), '', '0', 'RPA', '附件2文件格式不正确',
             AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '5', ''])
    else:
        if not file_flag2:
            audit_list.append(
                [str(bill_number), '报账点名称', str(rp_name), '', '0', 'RPA', '附件2电力明细清单不存在', '', '5', ''])
        else:

            bill_table_uname = str(bill_table_uname).replace('（', '(').replace('）', ')').replace('＃', '#')
            rp_name = str(rp_name).replace('（', '(').replace('）', ')').replace('＃', '#')
            if str(bill_table_uname).replace(' ', '').strip():
                if str(bill_table_uname).strip() in str(rp_name).strip() or str(rp_name).strip() in str(
                        bill_table_uname).strip():
                    audit_list.append(
                        [str(bill_number), '报账点名称', str(rp_name), str(bill_table_uname), '1', 'RPA', '合格',
                         AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '4', ''])
                else:
                    # auditResult.auditStatus = '不通过'  # 返回稽核结果为不通过
                    # audit_refused_type['信息与明细不符'] = 0
                    audit_list.append(
                        [str(bill_number), '报账点名称', str(rp_name), str(bill_table_uname), '0', 'RPA',
                         '报账点名称与电力清单中名称不一致',
                         AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '4', ''])
            else:
                # auditResult.auditStatus = '审核中'  # 返回稽核结果为转人工
                audit_list.append([str(bill_number), '报账点名称', str(rp_name), str(bill_table_uname), '0', 'RPA',
                                   '报账点名称识别失败', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '4', ''])
    return audit_list

"""
    稽核规则三：【数据稽核】
        页面【实际报账金额】与附件2（以户号为依据）的金额判断，必须完全一致
                #       细化稽核规则：（1）报账点电费-铁塔电费：页面【实际报账金额】=附件2（以电表户号为依据）的金额*页面分摊比例，必须完全一致；
                #                   （2）报账点电费-自维电费：页面【实际报账金额】=附件2（以电表户号为依据）的金额*工单中录入的本次实际分摊比例，必须完全一致；
                # ----  不一致后动作：【审核状态】-【不通过】，备注：【实际报账金额】与【电费明细】不一致
"""
def audit_rule_three(audit_list, auditResult, bill_number, rar_file, whether_execute, audit_refused_type,
                     file_flag2, payment_electric_info_actual_reimbursement_amount, affix_list_from_db,
                     payment_detail_info_data, bill_table_ele_charge, current_share_ratio, bill_table_data_list):
    """
    :param file_flag2:附件2是否存在
    :param payment_electric_info_actual_reimbursement_amount:实际报账金额
    :param affix_list_from_db:
    :param payment_detail_info_data: 电表信息
    :param bill_table_ele_charge: 【附件】-报账金额
    :param current_share_ratio: 分摊比例
    :param bill_table_data_list:
    :return:
    """

    if whether_execute == False:
        if '附件2' in rar_file:
            audit_list.append(
                [str(bill_number), '实际报账金额', str(payment_electric_info_actual_reimbursement_amount), '', '0', 'RPA',
                 '附件2文件格式不正确', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '5', ''])
        else:
            if not file_flag2:
                auditResult.auditStatus = '审核中'  # 返回稽核结果为转人工
                audit_list.append(
                    [str(bill_number), '实际报账金额', str(payment_electric_info_actual_reimbursement_amount), '', '0', 'RPA',
                     '附件2电力明细清单不存在', '', '5', ''])
            else:
                # if '铁塔' in page_business_activities:
                try:
                    shijijine = round(((float(bill_table_ele_charge) * float(current_share_ratio)) / 100), 2)
                    if shijijine != round(float(payment_electric_info_actual_reimbursement_amount), 2):
                        auditResult.auditStatus = '不通过'  # 返回稽核结果为不通过
                        audit_refused_type['金额有误'] = 0
                        audit_list.append(
                            [str(bill_number), '实际报账金额', str(payment_electric_info_actual_reimbursement_amount),
                             shijijine, '0', 'RPA',
                             '【实际报账金额】与【电费明细】不一致', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '1',
                             ''])
                    else:
                        audit_list.append(
                            [str(bill_number), '实际报账金额', str(payment_electric_info_actual_reimbursement_amount),
                             shijijine, '1', 'RPA', '合格',
                             AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '1', ''])
                except Exception as e:
                    auditResult.auditStatus = '审核中'
                    audit_list.append(
                        [str(bill_number), '实际报账金额', str(payment_electric_info_actual_reimbursement_amount),
                         str((bill_table_ele_charge)) + '*' + str(current_share_ratio) + '%', '0', 'RPA',
                         '【实际报账金额】与【电费明细】不一致', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '1', ''])
    else:
        try:
            if '附件2' in rar_file:
                audit_list.append(
                    [str(bill_number), '实际报账金额', str(
                        payment_electric_info_actual_reimbursement_amount), '',
                     '0', 'RPA',
                     '附件2文件格式不正确', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '5', ''])
            else:
                if not file_flag2:
                    auditResult.auditStatus = '审核中'  # 返回稽核结果为转人工
                    audit_list.append(
                        [str(bill_number), '实际报账金额', str(
                            payment_electric_info_actual_reimbursement_amount),
                         '', '0', 'RPA', '附件2电力明细清单不存在', '', '5', ''])
                else:
                    shijijine = 0
                    for data in payment_detail_info_data:
                        current_share_ratio = data['current_share_ratio']  # 页面【电费缴费明细信息】-【本次实际分摊比例】
                        current_share_ratio = re.findall(r"\d+\.?\d*", str(current_share_ratio).replace('%', ''))[0]
                        bill_table_ele_charge = '0'
                        for bill_table_data in bill_table_data_list:  # 通过户号识别结果列表找到对应的识别内容
                            if str(bill_table_data[0]) == str(data['es_number']):
                                if bill_table_data[1] != '':
                                    bill_table_ele_charge = bill_table_data[1]['ele_charge']  # 附件2（以户号为依据）的金额
                        try:
                            shijijine = round((((float(bill_table_ele_charge) * float(
                                current_share_ratio)) / 100) + float(shijijine)), 2)
                        except:
                            pass
                    if shijijine != round(float(payment_electric_info_actual_reimbursement_amount), 2):
                        auditResult.auditStatus = '不通过'  # 返回稽核结果为不通过
                        audit_refused_type['金额有误'] = 0
                        audit_list.append([str(bill_number), '实际报账金额',
                                           str(payment_electric_info_actual_reimbursement_amount),
                                           shijijine, '0', 'RPA',
                                           '【实际报账金额】与【电费明细】不一致',
                                           AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '1',
                                           ''])
                    else:
                        audit_list.append([str(bill_number), '实际报账金额',
                                           str(payment_electric_info_actual_reimbursement_amount),
                                           shijijine, '1', 'RPA', '合格',
                                           AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '1',
                                           ''])
        except Exception as e:
            auditResult.auditStatus = '审核中'
            audit_list.append([str(bill_number), '实际报账金额', str(payment_electric_info_actual_reimbursement_amount),
                               str((bill_table_ele_charge)) + '*' + str(current_share_ratio) + '%', '0', 'RPA',
                               'RPA处理异常', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '1', ''])
    return audit_list, auditResult,audit_refused_type

"""
    稽核规则五：【数据稽核】
        页面【电费缴费明细信息】-【本次实际分摊比例】与附件3的【报账点名称】的【移动】（分摊比例）
                # ----   不一致后动作：【审核状态】-【不通过】，备注：系统中录入的分摊比例与附件不一致
                # ----   自维电费报账点不一致后动作：【审核状态】-【不通过】，备注：系统中录入的分摊比例不正确
"""
def audit_rule_five(auditResult, audit_list, whether_execute, bill_number, rar_file, audit_refused_type, all_file,
                    payment_detail_info_data, file_flag3, current_share_ratio, affix_list_from_db, execute_list,
                    es_number,page_business_activities):
    """
    :param all_file: 附件信息
    :param payment_detail_info_data: 电表信息
    :param file_flag3:附件3是否存在
    :param current_share_ratio: 分摊比例
    :param affix_list_from_db:
    :param execute_list:
    :param es_number: 户号
    :return:
    """

    if whether_execute == False:
        try:
            if '非铁搭' in page_business_activities:
                if str(current_share_ratio).strip().replace('%', '') == '100':
                    audit_list.append(
                        [str(bill_number), '分摊比例', str(current_share_ratio), str(current_share_ratio),
                         '1',
                         'RPA', '合格', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件3'), '4', ''])
                else:
                    auditResult.auditStatus = '不通过'  # 返回稽核结果为不通过
                    audit_refused_type['信息与明细不符'] = 0
                    audit_list.append(
                        [str(bill_number), '分摊比例', str(current_share_ratio), str(current_share_ratio),
                         '0',
                         'RPA', '系统中录入的分摊比例-非铁塔的不为100%',
                         '非铁塔-分摊比例应为100%',
                         '4', ''])
            else:
                if '附件3' in rar_file:
                    auditResult.auditStatus = '审核中'  # 返回稽核结果为转人工
                    audit_list.append(
                        [str(bill_number), '分摊比例', str(current_share_ratio), '', '0', 'RPA', '附件3文件格式不正确',
                         AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件3'), '5', ''])
                else:
                    if not file_flag3:
                        auditResult.auditStatus = '审核中'  # 返回稽核结果为转人工
                        audit_list.append(
                            [str(bill_number), '分摊比例', str(current_share_ratio), '', '0', 'RPA', '附件3分摊比例不存在', '', '5', ''])
                    else:
                        att_3_name = all_file['附件3']
                        rpa_split_ratio_tablename = 'rpa_ocr_split_ratio'  # RPA分割比例记录表
                        rpa_split_ratio_sql = """SELECT * FROM """ + rpa_split_ratio_tablename + """ WHERE affixx_name='""" + att_3_name + """' AND door_no='""" + es_number + """'"""
                        rpa_split_ratio_data = PyMysql().get_db_data(rpa_split_ratio_sql)
                        if not rpa_split_ratio_data and len(rpa_split_ratio_data) == 0:
                            auditResult.auditStatus = '审核中'  # 返回稽核结果为转人工
                            audit_list.append(
                                [str(bill_number), '分摊比例', str(current_share_ratio), '', '0', 'RPA', '识别失败',
                                 AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件3'), '4', ''])
                        else:
                            yidong_split_ratio = str(rpa_split_ratio_data[0]['split_ratio']).strip().replace('%',
                                                                                                             '')  # 移动分割比例
                            # if float(str(yidong_split_ratio).strip().replace('%', '')) != float(str(current_share_ratio).strip().replace('%', '')):
                            if str(current_share_ratio).strip().replace('%', '') in str(yidong_split_ratio).strip().replace(
                                    '%', '') or str(yidong_split_ratio).strip().replace('%', '') in str(
                                    current_share_ratio).strip().replace('%', ''):
                                audit_list.append(
                                    [str(bill_number), '分摊比例', str(current_share_ratio), str(yidong_split_ratio),
                                     '1',
                                     'RPA', '合格', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件3'), '4', ''])
                            else:
                                auditResult.auditStatus = '不通过'  # 返回稽核结果为不通过
                                audit_refused_type['信息与明细不符'] = 0
                                audit_list.append(
                                    [str(bill_number), '分摊比例', str(current_share_ratio), str(yidong_split_ratio),
                                     '0',
                                     'RPA', '系统中录入的分摊比例与附件不一致',
                                     AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件3'),
                                     '4', ''])
        except Exception as e:
            # print(e)
            audit_list.append(
                [str(bill_number), '分摊比例', str(current_share_ratio), str(yidong_split_ratio), '0', 'RPA',
                 'RPA处理异常', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件3'), '4', ''])
            auditResult.auditStatus = '审核中'  # 转人工
    else:
        for data in payment_detail_info_data:
            current_share_ratio = data['current_share_ratio']  # 页面【电费缴费明细信息】-【本次实际分摊比例】
            current_share_ratio = re.findall(r"\d+\.?\d*", str(current_share_ratio).replace('%', ''))[0]
            try:
                if '非铁搭' in page_business_activities:
                    if current_share_ratio == '100':
                        audit_list.append(
                            [str(bill_number), '分摊比例', str(current_share_ratio), str(current_share_ratio),
                             '1',
                             'RPA', '合格', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件3'), '4', ''])
                    else:
                        auditResult.auditStatus = '不通过'  # 返回稽核结果为不通过
                        audit_refused_type['信息与明细不符'] = 0
                        audit_list.append(
                            [str(bill_number), '分摊比例', str(current_share_ratio), str(current_share_ratio),
                             '0',
                             'RPA', '系统中录入的分摊比例-非铁塔的不为100%',
                             '非铁塔-分摊比例应为100%',
                             '4', ''])
                else:
                    if '附件3' in rar_file:
                        auditResult.auditStatus = '审核中'  # 返回稽核结果为转人工
                        audit_list.append(
                            [str(bill_number), '分摊比例',
                             '【' + str(data['es_number']) + '】' + str(current_share_ratio), '', '0', 'RPA',
                             '附件3文件格式不正确',
                             AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件3'), '5', ''])
                    else:
                        if not file_flag3:
                            auditResult.auditStatus = '审核中'  # 返回稽核结果为转人工
                            audit_list.append(
                                [str(bill_number), '分摊比例',
                                 '【' + str(data['es_number']) + '】' + str(current_share_ratio), '', '0',
                                 'RPA',
                                 '附件3分摊比例不存在', '',
                                 '5', ''])
                        else:
                            att_3_name = all_file['附件3']
                            rpa_split_ratio_tablename = 'rpa_ocr_split_ratio'  # RPA分割比例记录表
                            rpa_split_ratio_sql = """SELECT * FROM """ + rpa_split_ratio_tablename + """ WHERE affixx_name='""" + att_3_name + """' AND door_no='""" + str(
                                data['es_number']) + """'"""
                            rpa_split_ratio_data = PyMysql().get_db_data(rpa_split_ratio_sql)
                            if not rpa_split_ratio_data and len(rpa_split_ratio_data) == 0:
                                auditResult.auditStatus = '审核中'  # 返回稽核结果为转人工
                                audit_list.append(
                                    [str(bill_number), '分摊比例',
                                     '【' + str(data['es_number']) + '】' + str(current_share_ratio), '', '0',
                                     'RPA',
                                     '识别失败',
                                     AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件3'), '4', ''])
                            else:
                                es_number_row = 0
                                for execute_list_data in execute_list:
                                    if str(execute_list_data[0]) == str(data['es_number']):
                                        es_number_row = execute_list_data[1]
                                yidong_split_ratio = str(
                                    rpa_split_ratio_data[es_number_row]['split_ratio']).strip().replace('%', '')  # 移动分割比例
                                # if float(str(yidong_split_ratio).strip().replace('%', '')) != float(str(current_share_ratio).strip().replace('%', '')):
                                if str(current_share_ratio).strip().replace('%', '') in str(
                                        yidong_split_ratio).strip().replace('%', '') or str(
                                        yidong_split_ratio).strip().replace('%', '') in str(
                                        current_share_ratio).strip().replace('%', ''):
                                    audit_list.append([str(bill_number), '分摊比例',
                                                       '【' + str(data['es_number']) + '】' + str(current_share_ratio),
                                                       str(yidong_split_ratio), '1', 'RPA', '合格',
                                                       AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件3'), '4',
                                                       ''])
                                else:
                                    auditResult.auditStatus = '不通过'  # 返回稽核结果为不通过
                                    audit_refused_type['信息与明细不符'] = 0
                                    audit_list.append(
                                        [str(bill_number), '分摊比例',
                                         '【' + str(data['es_number']) + '】' + str(current_share_ratio),
                                         str(yidong_split_ratio),
                                         '0',
                                         'RPA', '系统中录入的分摊比例与附件不一致',
                                         AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件3'),
                                         '4', ''])
            except Exception as e:
                # print(e)
                audit_list.append(
                    [str(bill_number), '分摊比例',
                     '【' + str(data['es_number']) + '】' + str(current_share_ratio),
                     str(yidong_split_ratio), '0',
                     'RPA',
                     'RPA处理异常', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件3'), '4', ''])
                auditResult.auditStatus = '审核中'  # 转人工
    return audit_list, auditResult,audit_refused_type

"""
    稽核规则六:【数据稽核】
        页面【电表缴费明细信息】-【本期读数（度）】与附件2根据页面【电表缴费明细信息】-【户号】查找对应的【本期指示】/【本月】等等
                # ----   不一致后动作：【审核状态】-【不通过】，备注：本期读数与电费明细不一致
"""
def audit_rule_six(audit_list, auditResult, rar_file, whether_execute, bill_number, audit_refused_type,
                   affix_list_from_db,
                   payment_detail_info_data, current_reading, file_flag2, bill_table_data, bill_table_data_list):
    """
    :param current_reading: 本期读数
    :param file_flag2:附件2是否存在
    :param bill_table_data: 附件识别后信息
    :return:
    """
    if whether_execute == False:
        try:
            if '附件2' in rar_file:
                audit_list.append(
                    [str(bill_number), '本期读数', str(current_reading), '', '0', 'RPA', '附件2文件格式不正确',
                     AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '5', ''])
            else:
                if not file_flag2:
                    audit_list.append(
                        [str(bill_number), '本期读数', str(current_reading), '', '0', 'RPA', '附件2电力明细清单不存在', '', '5', ''])
                else:
                    now_display_num = bill_table_data[0]['now_display_num']  # 【本期指示】/【本月】/本次抄见示数
                    if not now_display_num or now_display_num == '':
                        # 此规则与规则八相矛盾
                        auditResult.auditStatus = '审核中'  # 转人工
                        audit_list.append(
                            [str(bill_number), '本期读数', str(current_reading), str(now_display_num), '0', 'RPA',
                             '附件2【本期指示】/【本月】数据OCR未识别出', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'),
                             '4',
                             ''])
                        pass
                    elif abs(float(str(current_reading).strip()) - float(str(now_display_num).strip())) > 0.01:
                        auditResult.auditStatus = '不通过'  # 返回稽核结果为不通过
                        audit_refused_type['信息与明细不符'] = 0
                        audit_list.append(
                            [str(bill_number), '本期读数', str(current_reading), str(now_display_num), '0', 'RPA',
                             '本期读数与电费明细不一致', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '4', ''])
                    else:
                        audit_list.append(
                            [str(bill_number), '本期读数', str(current_reading), str(now_display_num), '1', 'RPA',
                             '合格',
                             AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'),
                             '4', ''])
        except Exception as e:
            # print(e)
            auditResult.auditStatus = '审核中'  # 返回稽核结果为转人工
            audit_list.append(
                [str(bill_number), '本期读数', str(current_reading), str(now_display_num), '0', 'RPA',
                 'RPA处理异常', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '4', ''])
    else:
        for data in payment_detail_info_data:
            now_display_num = ''
            current_reading = data['current_reading']  # 页面【电表缴费明细信息】-【本期读数（度）】
            try:
                if '附件2' in rar_file:
                    audit_list.append(
                        [str(bill_number), '本期读数', '【' + str(data['es_number']) + '】' + str(current_reading), '', '0',
                         'RPA', '附件2文件格式不正确', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '5', ''])
                else:
                    if not file_flag2:
                        audit_list.append(
                            [str(bill_number), '本期读数', '【' + str(data['es_number']) + '】' + str(current_reading), '',
                             '0', 'RPA', '附件2电力明细清单不存在', '', '5', ''])
                    else:
                        for bill_table_data in bill_table_data_list:  # 通过户号识别结果列表找到对应的识别内容
                            if str(bill_table_data[0]) == str(data['es_number']):
                                if bill_table_data[1] != '':
                                    now_display_num = bill_table_data[1]['now_display_num']  # 【本期指示】/【本月】/本次抄见示数
                        if not now_display_num or now_display_num == '':
                            # 此规则与规则八相矛盾
                            auditResult.auditStatus = '审核中'  # 转人工
                            audit_list.append(
                                [str(bill_number), '本期读数', '【' + str(data['es_number']) + '】' + str(current_reading),
                                 str(now_display_num), '0', 'RPA',
                                 '附件2【本期指示】/【本月】数据OCR未识别出',
                                 AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '4',
                                 ''])
                            pass
                        elif float(str(current_reading).strip()) != float(str(now_display_num).strip()):
                            auditResult.auditStatus = '不通过'  # 返回稽核结果为不通过
                            audit_refused_type['信息与明细不符'] = 0
                            audit_list.append(
                                [str(bill_number), '本期读数', '【' + str(data['es_number']) + '】' + str(current_reading),
                                 str(now_display_num), '0', 'RPA',
                                 '本期读数与电费明细不一致', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '4',
                                 ''])
                        else:
                            audit_list.append(
                                [str(bill_number), '本期读数', '【' + str(data['es_number']) + '】' + str(current_reading),
                                 str(now_display_num), '1', 'RPA',
                                 '合格',
                                 AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'),
                                 '4', ''])
            except Exception as e:
                # print(e)
                auditResult.auditStatus = '审核中'  # 返回稽核结果为转人工
                audit_list.append(
                    [str(bill_number), '本期读数', '【' + str(data['es_number']) + '】' + str(current_reading),
                     str(now_display_num), '0', 'RPA',
                     'RPA处理异常', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '4', ''])
    return audit_list, auditResult,audit_refused_type

"""
    稽核规则十四:【数据稽核 - 上期读数】
        页面【电表缴费明细信息】-【本期读数（度）】与附件2根据页面【电表缴费明细信息】-【户号】查找对应的【本期指示】/【本月】等等
                # ----   不一致后动作：【审核状态】-【不通过】，备注：本期读数与电费明细不一致
"""
def audit_rule_fourteen(audit_list, auditResult, rar_file, whether_execute, bill_number, audit_refused_type,
                   affix_list_from_db,
                   payment_detail_info_data, last_reading, file_flag2, bill_table_data, bill_table_data_list):
    """
    :param current_reading: 本期读数
    :param file_flag2:附件2是否存在
    :param bill_table_data: 附件识别后信息
    :return:
    """
    if whether_execute == False:
        try:
            if '附件2' in rar_file:
                audit_list.append(
                    [str(bill_number), '上期读数', str(last_reading), '', '0', 'RPA', '附件2文件格式不正确',
                     AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '5', ''])
            else:
                if not file_flag2:
                    audit_list.append(
                        [str(bill_number), '上期读数', str(last_reading), '', '0', 'RPA', '附件2电力明细清单不存在', '', '5', ''])
                else:
                    last_display_num = bill_table_data[0]['last_display_num']  # 【本期指示】/【本月】/本次抄见示数
                    if not last_display_num or last_display_num == '':
                        # 此规则与规则八相矛盾
                        auditResult.auditStatus = '审核中'  # 转人工
                        audit_list.append(
                            [str(bill_number), '上期读数', str(last_reading), str(last_display_num), '0', 'RPA',
                             '附件2【上期指示】/【本月】数据OCR未识别出', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'),
                             '4',
                             ''])
                        pass
                    elif abs(float(str(last_reading).strip()) - float(str(last_display_num).strip())) > 0.01:
                        auditResult.auditStatus = '不通过'  # 返回稽核结果为不通过
                        audit_refused_type['信息与明细不符'] = 0
                        audit_list.append(
                            [str(bill_number), '上期读数', str(last_reading), str(last_display_num), '0', 'RPA',
                             '上期读数与电费明细不一致', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '4', ''])
                    else:
                        audit_list.append(
                            [str(bill_number), '上期读数', str(last_reading), str(last_display_num), '1', 'RPA',
                             '合格',
                             AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'),
                             '4', ''])
        except Exception as e:
            # print(e)
            auditResult.auditStatus = '审核中'  # 返回稽核结果为转人工
            audit_list.append(
                [str(bill_number), '上期读数', str(last_reading), str(last_display_num), '0', 'RPA',
                 'RPA处理异常', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '4', ''])
    else:
        for data in payment_detail_info_data:
            last_display_num = ''
            last_reading = data['last_reading']  # 页面【电表缴费明细信息】-【本期读数（度）】
            try:
                if '附件2' in rar_file:
                    audit_list.append(
                        [str(bill_number), '上期读数', '【' + str(data['es_number']) + '】' + str(last_reading), '', '0',
                         'RPA', '附件2文件格式不正确', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '5', ''])
                else:
                    if not file_flag2:
                        audit_list.append(
                            [str(bill_number), '上期读数', '【' + str(data['es_number']) + '】' + str(last_reading), '',
                             '0', 'RPA', '附件2电力明细清单不存在', '', '5', ''])
                    else:
                        for bill_table_data in bill_table_data_list:  # 通过户号识别结果列表找到对应的识别内容
                            if str(bill_table_data[0]) == str(data['es_number']):
                                if bill_table_data[1] != '':
                                    last_display_num = bill_table_data[1]['last_display_num']  # 【上期指示】/【上月】/上次抄见示数
                        if not last_display_num or last_display_num == '':
                            # 此规则与规则八相矛盾
                            auditResult.auditStatus = '审核中'  # 转人工
                            audit_list.append(
                                [str(bill_number), '上期读数', '【' + str(data['es_number']) + '】' + str(last_reading),
                                 str(last_display_num), '0', 'RPA',
                                 '附件2【上期指示】/【本月】数据OCR未识别出',
                                 AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '4',
                                 ''])
                            pass
                        elif float(str(last_reading).strip()) != float(str(last_display_num).strip()):
                            auditResult.auditStatus = '不通过'  # 返回稽核结果为不通过
                            audit_refused_type['信息与明细不符'] = 0
                            audit_list.append(
                                [str(bill_number), '上期读数', '【' + str(data['es_number']) + '】' + str(last_reading),
                                 str(last_display_num), '0', 'RPA',
                                 '上期读数与电费明细不一致', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '4',
                                 ''])
                        else:
                            audit_list.append(
                                [str(bill_number), '上期读数', '【' + str(data['es_number']) + '】' + str(last_reading),
                                 str(last_display_num), '1', 'RPA',
                                 '合格',
                                 AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'),
                                 '4', ''])
            except Exception as e:
                # print(e)
                auditResult.auditStatus = '审核中'  # 返回稽核结果为转人工
                audit_list.append(
                    [str(bill_number), '上期读数', '【' + str(data['es_number']) + '】' + str(last_reading),
                     str(last_display_num), '0', 'RPA',
                     'RPA处理异常', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '4', ''])
    return audit_list, auditResult,audit_refused_type

"""
    稽核规则七：【数据稽核】
        页面【电表缴费明细信息】-【电费单价（元/度）】与附件2根据页面【电表缴费明细信息】-【户号】查找对应的【电价】/【电费信息】之和等等
                # ----   不一致后动作：【审核状态】-【不通过】，备注：电费单价与电费明细不一致
"""
def audit_rule_seven(audit_list, auditResult, whether_execute, rar_file, affix_list_from_db, bill_number,
                     audit_refused_type,
                     file_flag2, payment_detail_info_data, bill_table_data_electricity_price, electricity_price,
                     bill_table_data_list):
    """
    :param file_flag2: 附件2是否存在
    :param payment_detail_info_data: 电表信息
    :param bill_table_data_electricity_price: 识别表电费单价
    :param electricity_price: 电费单价
    :param bill_table_data_list: 附件识别信息
    :return:
    """
    if whether_execute == False:
        try:
            if '附件2' in rar_file:
                audit_list.append(
                    [str(bill_number), '电费单价', str(electricity_price), '', '0', 'RPA',
                     '附件2文件格式不正确', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '5', ''])
            else:
                if not file_flag2:
                    audit_list.append(
                        [str(bill_number), '电费单价', str(electricity_price), '', '0', 'RPA',
                         '附件2电力明细清单不存在', '', '5', ''])
                else:
                    if bill_table_data_electricity_price:
                        # if ';' in bill_table_data_electricity_price:
                        #     bill_table_data_electricity_price = bill_table_data_electricity_price.split(';')[0]
                        select_data_list = PyMysql().select_eleinfo('payment_detail_info', 'payment_code',
                                                                    bill_number)
                        for sum, select_data in enumerate(select_data_list[0]):
                            if sum >= 1 and float(select_data) == 0:
                                continue
                            for price_sum, bill_table_data_electricity_price_value in enumerate(
                                    bill_table_data_electricity_price.split(';')):
                                if round(float(bill_table_data_electricity_price_value),
                                         4) != round(float(select_data), 4):
                                    if price_sum == len(
                                            bill_table_data_electricity_price.split(';')) - 1:
                                        auditResult.auditStatus = '不通过'  # 返回稽核结果为不通过
                                        audit_refused_type['信息与明细不符'] = 0
                                        audit_list.append(
                                            [str(bill_number), '电费单价', str(select_data),
                                             str(bill_table_data_electricity_price), '0', 'RPA',
                                             '电费单价与电费明细不一致',
                                             AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'),
                                             '4',
                                             ''])
                                else:
                                    audit_list.append(
                                        [str(bill_number), '电费单价', str(select_data),
                                         str(round(
                                             float(bill_table_data_electricity_price_value),
                                             4)), '1', 'RPA', '合格',
                                         AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'),
                                         '4', ''])
                                    break
                    else:
                        auditResult.auditStatus = '审核中'  # 返回稽核结果为转人工
                        audit_list.append(
                            [str(bill_number), '电费单价', str(electricity_price), '', '0', 'RPA',
                             '识别失败',
                             AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '4',
                             ''])
        except Exception as e:
            # print(e)
            auditResult.auditStatus = '审核中'  # 返回稽核结果为转人工
            audit_list.append(
                [str(bill_number), '电费单价', str(electricity_price),
                 str(bill_table_data_electricity_price), '0', 'RPA', 'RPA处理异常',
                 AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '4', ''])
    else:
        for data in payment_detail_info_data:
            electricity_price = data['electricity_price']
            try:
                if '附件2' in rar_file:
                    audit_list.append(
                        [str(bill_number), '电费单价',
                         '【' + str(data['es_number']) + '】' + str(electricity_price), '', '0',
                         'RPA', '附件2文件格式不正确',
                         AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '5', ''])
                else:
                    if not file_flag2:
                        audit_list.append(
                            [str(bill_number), '电费单价',
                             '【' + str(data['es_number']) + '】' + str(electricity_price), '',
                             '0', 'RPA', '附件2电力明细清单不存在', '', '5', ''])
                    else:
                        bill_table_data_electricity_price = ''
                        for bill_table_data in bill_table_data_list:  # 通过户号识别结果列表找到对应的识别内容
                            if str(bill_table_data[0]) == str(data['es_number']):
                                if bill_table_data[1] != '':
                                    bill_table_data_electricity_price = str(
                                        bill_table_data[1]['ele_price']).strip()  # 电价
                        if bill_table_data_electricity_price != '':
                            # if ';' in bill_table_data_electricity_price:
                            #     bill_table_data_electricity_price = bill_table_data_electricity_price.split(';')[0]
                            select_data_list = PyMysql().select_eleinfo1(data)
                            for sum, select_data in enumerate(select_data_list[0]):
                                if sum >= 1 and float(select_data) == 0:
                                    continue
                                for price_sum, bill_table_data_electricity_price in enumerate(
                                        bill_table_data_electricity_price.split(';')):
                                    if round(float(bill_table_data_electricity_price),
                                             4) != round(float(select_data), 4):
                                        if price_sum == len(
                                                bill_table_data_electricity_price.split(
                                                    ';')) - 1:
                                            auditResult.auditStatus = '不通过'  # 返回稽核结果为不通过
                                            audit_refused_type['信息与明细不符'] = 0
                                            audit_list.append([str(bill_number), '电费单价',
                                                               '【' + str(data[
                                                                             'es_number']) + '】' + str(
                                                                   select_data),
                                                               str(
                                                                   bill_table_data_electricity_price),
                                                               '0', 'RPA',
                                                               '电费单价与电费明细不一致',
                                                               AffixUtils.get_affix_url_with_name(
                                                                   affix_list_from_db, '附件2'),
                                                               '4',
                                                               ''])
                                    else:

                                        audit_list.append([
                                            str(bill_number), '电费单价',
                                            '【' + str(data['es_number']) + '】' + str(select_data),
                                            str(round(float(bill_table_data_electricity_price), 4)),
                                            '1', 'RPA', '合格',
                                            AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'),
                                            '4',
                                            ''])
                                        break
                        else:
                            auditResult.auditStatus = '审核中'  # 返回稽核结果为转人工
                            audit_list.append(
                                [str(bill_number), '电费单价',
                                 '【' + str(data['es_number']) + '】' + str(electricity_price),
                                 '', '0', 'RPA', '识别失败',
                                 AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '4',
                                 ''])
            except Exception as e:
                # print(e)
                auditResult.auditStatus = '审核中'  # 返回稽核结果为转人工
                audit_list.append(
                    [str(bill_number), '电费单价',
                     '【' + str(data['es_number']) + '】' + str(electricity_price),
                     str(bill_table_data_electricity_price), '0', 'RPA', 'RPA处理异常',
                     AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '4', ''])
    return audit_list, auditResult,audit_refused_type

"""
    稽核规则八：【数据稽核】
        如果【本期读数】判断通过：页面【电表缴费明细信息】-【用电量（度）】=（【本期读数（度）】减去【上期读数（度）】）* 电表倍率 * 本次实际分摊比例（取页面的分摊比例），此条规则需完全一致。
                #        如果附件2无【本期读数】：页面【电表缴费明细信息】-【用电量（度）】+（【电损电量】/【本次实际分摊比例】（取页面的分摊比例））=附件2根据页面【电表缴费明细信息】-【户号】查找对应的【总结算电量】，
                #        总电量不包含电损的情况：页面【电表缴费明细信息】-【用电量（度）】=附件2根据页面【电表缴费明细信息】-【户号】查找对应的【电量】 * 本次实际分摊比例（取页面的分摊比例）。
                #        具体是那种情况，需在票据学习时区分附件2中电量是否包括电损。
                #        后面2条规则四舍五入匹配，相差±1度均可判断通过。
                # ----   不一致后动作：【审核状态】-【不通过】，备注：用电量与电费明细不一致
"""
def audit_rule_eight(auditResult, audit_list, audit_refused_type, whether_execute, rar_file, bill_number, file_flag2,
                     electricity_consumption, affix_list_from_db, bill_table_now_display_num, ocr_electricity_loss,
                     payment_detail_info_data, now_display_num, last_reading, es_magnification, current_share_ratio,
                     electricity_consumption_list, bill_table_last_display_num, bill_table_data_list):
    """
    :param electricity_consumption:用电量
    :param affix_list_from_db:
    :param bill_table_now_display_num: 本期读数
    :param ocr_electricity_loss: 电损
    :param payment_detail_info_data:
    :param now_display_num: 【本期指示】/【本月】/本次抄见示数
    :param last_reading: 上期读数
    :param es_magnification: 电表倍率
    :param current_share_ratio:本次实际分摊比例
    :param electricity_consumption_list: 用电量(多个)
    :param bill_table_last_display_num: 附件2上期读数
    :return:
    """
    if whether_execute == False:
        try:
            if '附件2' in rar_file:
                audit_list.append([str(bill_number), '用电量', str(electricity_consumption), '', '0', 'RPA', '附件2文件格式不正确',
                                   AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '5', ''])
            else:
                if not file_flag2:
                    audit_list.append(
                        [str(bill_number), '用电量', str(electricity_consumption), '', '0', 'RPA', '附件2电力明细清单不存在', '', '5',
                         ''])
                else:
                    if now_display_num and bill_table_last_display_num:
                        audit_list.append(
                                            [str(bill_number), '用电量', str(electricity_consumption), '附件【本期读数/上期读数】存在', '1',
                                             'RPA', '合格', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'),
                                            '4', ''])
                    else:
                        select_data_list = PyMysql().select_eleinfo('payment_detail_info', 'payment_code', bill_number)
                        electricity_consumption_list = select_data_list[1]  # 页面【电表缴费明细信息】-【用电量（度）】 拆分成list循环对比
                        electricity_loss_list = select_data_list[1]  # 页面【电表缴费明细信息】-【电损（度）】 拆分成list循环对比
                        n_1 = (round(float(sum(electricity_consumption_list)), 2) + round(
                            float(sum(electricity_loss_list)), 2)) / (current_share_ratio /100)
                        if ocr_electricity_loss == n_1:
                            audit_list.append([str(bill_number), '用电量', str(n_1),
                                               str(ocr_electricity_loss),
                                               '1', 'RPA', '合格',
                                               AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'),
                                               '4', ''])
                        else:
                            auditResult.auditStatus = '不通过'  # 返回稽核结果为不通过
                            audit_refused_type['信息与明细不符'] = 0
                            audit_list.append(
                                [str(bill_number), '用电量', str(n_1),
                                 str(ocr_electricity_loss), '0', 'RPA', '用电量与电费明细不一致',
                                 AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '4', ''])
        except Exception as e:
            # print(e)
            auditResult.auditStatus = '审核中'  # 返回稽核结果为转人工
            audit_list.append(
                [str(bill_number), '用电量', str(electricity_consumption), '', '0', 'RPA', 'RPA处理异常',
                 AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '4', ''])
    else:
        for data in payment_detail_info_data:
            try:
                electricity_consumption = data['electricity_consumption']
                current_share_ratio = data['current_share_ratio']
                current_share_ratio = re.findall(r"\d+\.?\d*", str(current_share_ratio).replace('%', ''))[0]
                ocr_electricity_loss = '0'
                bill_table_last_display_num = ''
                bill_table_now_display_num = ''
                for bill_table_data in bill_table_data_list:  # 通过户号识别结果列表找到对应的识别内容
                    if str(bill_table_data[0]) == str(data['es_number']):
                        if bill_table_data[1] != '':
                            ocr_electricity_loss = str(bill_table_data[1]['ele_loss'])  # OCR识别保存的电损
                            bill_table_last_display_num = str(bill_table_data[1]['last_display_num'])  # 附件2上期读数
                            bill_table_now_display_num = str(bill_table_data[1]['now_display_num'])  # 附件2 - 本期读数
                if '附件2' in rar_file:
                    audit_list.append(
                        [str(bill_number), '用电量', '【' + str(data['es_number']) + '】' + str(electricity_consumption), '',
                         '0', 'RPA', '附件2文件格式不正确', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '5',
                         ''])
                else:
                    if not file_flag2:
                        audit_list.append(
                            [str(bill_number), '用电量', '【' + str(data['es_number']) + '】' + str(electricity_consumption),
                             '', '0', 'RPA', '附件2电力明细清单不存在', '', '5', ''])
                    else:
                        if bill_table_now_display_num and bill_table_last_display_num:
                            audit_list.append(
                                [str(bill_number), '用电量', str(electricity_consumption), '附件【本期读数/上期读数】存在', '1',
                                 'RPA', '合格', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'),
                                 '4', ''])
                        else:
                            select_data_list = PyMysql().select_eleinfo1(data)
                            electricity_consumption_list = select_data_list[1]  # 页面【电表缴费明细信息】-【用电量（度）】 拆分成list循环对比
                            electricity_loss_list = select_data_list[1]  # 页面【电表缴费明细信息】-【电损（度）】 拆分成list循环对比
                            n_1 = (round(float(sum(electricity_consumption_list)), 2) + round(
                                float(sum(electricity_loss_list)), 2)) / (current_share_ratio /100)
                            if ocr_electricity_loss == n_1:
                                audit_list.append([str(bill_number), '用电量', str(n_1),
                                                   str(ocr_electricity_loss),
                                                   '1', 'RPA', '合格',
                                                   AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'),
                                                   '4', ''])
                            else:
                                auditResult.auditStatus = '不通过'  # 返回稽核结果为不通过
                                audit_refused_type['信息与明细不符'] = 0
                                audit_list.append(
                                    [str(bill_number), '用电量', str(n_1),
                                     str(ocr_electricity_loss), '0', 'RPA', '用电量与电费明细不一致',
                                     AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '4', ''])
            except Exception as e:
                auditResult.auditStatus = '审核中'  # 返回稽核结果为转人工
                audit_list.append(
                    [str(bill_number), '用电量', '【' + str(data['es_number']) + '】' + str(electricity_consumption), '',
                     '0', 'RPA', 'RPA处理异常', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '4', ''])

    return audit_list, auditResult,audit_refused_type
# def audit_rule_eight(auditResult, audit_list, audit_refused_type, whether_execute, rar_file, bill_number, file_flag2,
#                      electricity_consumption, affix_list_from_db, bill_table_now_display_num, ocr_electricity_loss,
#                      payment_detail_info_data, now_display_num, last_reading, es_magnification, current_share_ratio,
#                      electricity_consumption_list, bill_table_last_display_num, bill_table_data_list):
#     """
#     :param electricity_consumption:用电量
#     :param affix_list_from_db:
#     :param bill_table_now_display_num: 本期读数
#     :param ocr_electricity_loss: 电损
#     :param payment_detail_info_data:
#     :param now_display_num: 【本期指示】/【本月】/本次抄见示数
#     :param last_reading: 上期读数
#     :param es_magnification: 电表倍率
#     :param current_share_ratio:本次实际分摊比例
#     :param electricity_consumption_list: 用电量(多个)
#     :param bill_table_last_display_num: 附件2上期读数
#     :return:
#     """
#     if whether_execute == False:
#         try:
#             if '附件2' in rar_file:
#                 audit_list.append([str(bill_number), '用电量', str(electricity_consumption), '', '0', 'RPA', '附件2文件格式不正确',
#                                    AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '5', ''])
#             elif bill_table_now_display_num == '' or bill_table_last_display_num == '':
#                 auditResult.auditStatus = '审核中'  # 转人工
#                 audit_list.append(
#                     [str(bill_number), '用电量', str(electricity_consumption), '', '0',
#                      'RPA',
#                      '附件2【本期指示】/【本月】数据OCR未识别出',
#                      AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '4',
#                      ''])
#             else:
#                 if not file_flag2:
#                     audit_list.append(
#                         [str(bill_number), '用电量', str(electricity_consumption), '', '0', 'RPA', '附件2电力明细清单不存在', '', '5',
#                          ''])
#                 else:
#                     if ocr_electricity_loss and float(ocr_electricity_loss) > 0:
#                         # 包含电损
#                         # 判断附件2是否有【本期读数】
#                         if now_display_num != '0.0':
#                             ele_count = round(((float(now_display_num) - float(last_reading)) * float(
#                                 str(es_magnification).strip()) * float(current_share_ratio)) / 100, 2)
#                             for sum, electricity_consumption_data in enumerate(electricity_consumption_list):
#                                 if sum >= 1 and float(electricity_consumption_data) == 0:
#                                     continue
#                                 if int(round(float(electricity_consumption_data), 2) - ele_count) <= 1:
#                                     # 有电损有本期读数通过
#                                     audit_list.append(
#                                         [str(bill_number), '用电量', str(electricity_consumption), str(ele_count), '1',
#                                          'RPA', '合格', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'),
#                                          '4', ''])
#                                 else:
#                                     # 有电损不通过
#                                     auditResult.auditStatus = '不通过'  # 返回稽核结果为不通过
#                                     audit_refused_type['信息与明细不符'] = 0
#                                     audit_list.append(
#                                         [str(bill_number), '用电量', str(electricity_consumption), str(ele_count), '0',
#                                          'RPA', '用电量与电费明细不一致',
#                                          AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '4', ''])
#                         else:
#                             for sum, electricity_consumption_data in enumerate(electricity_consumption_list):
#                                 n_1 = round((float(ocr_electricity_loss)+ float(
#                                     electricity_consumption_data)) / (
#                                         float(current_share_ratio) / 100) , 2)
#                                 if sum >= 1 and float(electricity_consumption_data) == 0:
#                                     continue
#                                 if abs(n_1 - float(electricity_consumption_data)) <= 1:
#                                     # 有电损通过
#                                     audit_list.append(
#                                         [str(bill_number), '用电量', str(electricity_consumption), str(n_1), '1', 'RPA',
#                                          '合格', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '4', ''])
#                                 else:
#                                     # 有电损不通过
#                                     auditResult.auditStatus = '不通过'  # 返回稽核结果为不通过
#                                     audit_refused_type['信息与明细不符'] = 0
#                                     audit_list.append(
#                                         [str(bill_number), '用电量', str(electricity_consumption), str(n_1), '0', 'RPA',
#                                          '用电量与电费明细不一致',
#                                          AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '4', ''])
#                     else:
#
#                         # 不包含电损
#                         bill_table_display_num_result = (
#                                     (float(bill_table_now_display_num) - float(bill_table_last_display_num)) * (
#                                         float(current_share_ratio) / 100) * es_magnification)
#                         for sum, electricity_consumption_data in enumerate(electricity_consumption_list):
#                             if sum >= 1 and float(electricity_consumption_data) == 0:
#                                 continue
#                             if abs(bill_table_display_num_result - float(electricity_consumption_data)) > 1:
#                                 # 无电损不通过
#                                 auditResult.auditStatus = '不通过'  # 返回稽核结果为不通过
#                                 audit_refused_type['信息与明细不符'] = 0
#                                 audit_list.append([str(bill_number), '用电量', str(electricity_consumption_data),
#                                                    str(bill_table_display_num_result), '0', 'RPA',
#                                                    '用电量与电费明细不一致',
#                                                    AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '4',
#                                                    ''])
#                             else:
#                                 audit_list.append([str(bill_number), '用电量', str(electricity_consumption_data),
#                                                    str(bill_table_display_num_result), '1', 'RPA',
#                                                    '合格',
#                                                    AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '4',
#                                                    ''])
#         except Exception as e:
#             # print(e)
#             auditResult.auditStatus = '审核中'  # 返回稽核结果为转人工
#             audit_list.append(
#                 [str(bill_number), '用电量', str(electricity_consumption), '', '0', 'RPA', 'RPA处理异常',
#                  AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '4', ''])
#     else:
#         for data in payment_detail_info_data:
#             try:
#                 electricity_consumption = data['electricity_consumption']
#                 es_magnification = data['es_magnification']
#                 current_share_ratio = data['current_share_ratio']
#                 current_share_ratio = re.findall(r"\d+\.?\d*", str(current_share_ratio).replace('%', ''))[0]
#                 last_reading = payment_detail_info_data[0]['last_reading']  # 页面【电表缴费明细信息】- 【上期读数（度）】
#                 ocr_electricity_loss = '0'
#                 now_display_num = ''
#                 bill_table_last_display_num = ''
#                 bill_table_now_display_num = ''
#                 for bill_table_data in bill_table_data_list:  # 通过户号识别结果列表找到对应的识别内容
#                     if str(bill_table_data[0]) == str(data['es_number']):
#                         if bill_table_data[1] != '':
#                             now_display_num = str(bill_table_data[1]['now_display_num'])  # 【本期指示】/【本月】/本次抄见示数
#                             ocr_electricity_loss = str(bill_table_data[1]['ele_loss'])  # OCR识别保存的电损
#                             bill_table_last_display_num = str(bill_table_data[1]['last_display_num'])  # 附件2上期读数
#                             bill_table_now_display_num = str(bill_table_data[1]['now_display_num'])  # 附件2 - 本期读数
#                 if '附件2' in rar_file:
#                     audit_list.append(
#                         [str(bill_number), '用电量', '【' + str(data['es_number']) + '】' + str(electricity_consumption), '',
#                          '0', 'RPA', '附件2文件格式不正确', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '5',
#                          ''])
#                 elif bill_table_now_display_num == '' or bill_table_last_display_num == '':
#                     auditResult.auditStatus = '审核中'  # 转人工
#                     audit_list.append(
#                         [str(bill_number), '用电量', '【' + str(data['es_number']) + '】' + str(electricity_consumption), '',
#                          '0',
#                          'RPA',
#                          '附件2【本期指示】/【本月】数据OCR未识别出',
#                          AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '4',
#                          ''])
#                 else:
#                     if not file_flag2:
#                         audit_list.append(
#                             [str(bill_number), '用电量', '【' + str(data['es_number']) + '】' + str(electricity_consumption),
#                              '', '0', 'RPA', '附件2电力明细清单不存在', '', '5', ''])
#                     else:
#                         select_data_list = PyMysql().select_eleinfo1(data)
#                         electricity_consumption_list = select_data_list[1]  # 页面【电表缴费明细信息】-【用电量（度）】 拆分成list循环对比
#                         if ocr_electricity_loss and float(ocr_electricity_loss) > 0:
#                             # 包含电损
#                             # 判断附件2是否有【本期读数】
#                             if now_display_num != '' and now_display_num != '0.0':
#                                 ele_count = round(((float(now_display_num) - float(last_reading)) * float(
#                                     str(es_magnification).strip()) * float(current_share_ratio)) / 100, 2)
#                                 for sum, electricity_consumption_data in enumerate(electricity_consumption_list):
#                                     if sum >= 1 and float(electricity_consumption_data) == 0:
#                                         continue
#                                     if int(round(float(electricity_consumption_data), 2) - ele_count) <= 1:
#                                         # 有电损有本期读数通过
#                                         audit_list.append([str(bill_number), '用电量',
#                                                            '【' + str(data['es_number']) + '】' + str(
#                                                                electricity_consumption), str(ele_count), '1', 'RPA',
#                                                            '合格', AffixUtils.get_affix_url_with_name(affix_list_from_db,
#                                                                                                     '附件2'), '4', ''])
#                                     else:
#                                         # 有电损不通过
#                                         auditResult.auditStatus = '不通过'  # 返回稽核结果为不通过
#                                         audit_refused_type['信息与明细不符'] = 0
#                                         audit_list.append([str(bill_number), '用电量',
#                                                            '【' + str(data['es_number']) + '】' + str(
#                                                                electricity_consumption), str(ele_count), '0', 'RPA',
#                                                            '用电量与电费明细不一致',
#                                                            AffixUtils.get_affix_url_with_name(affix_list_from_db,
#                                                                                               '附件2'), '4', ''])
#                             else:
#                                 for sum, electricity_consumption_data in enumerate(electricity_consumption_list):
#                                     n_1 = round((float(ocr_electricity_loss) + float(
#                                         electricity_consumption_data)) / (
#                                                         float(current_share_ratio) / 100), 2)
#                                     if sum >= 1 and float(electricity_consumption_data) == 0:
#                                         continue
#                                     if abs(n_1 - float(electricity_consumption_data)) <= 1:
#                                         # 有电损通过
#                                         audit_list.append([str(bill_number), '用电量',
#                                                            '【' + str(data['es_number']) + '】' + str(
#                                                                electricity_consumption), str(n_1), '1', 'RPA', '合格',
#                                                            AffixUtils.get_affix_url_with_name(affix_list_from_db,
#                                                                                               '附件2'), '4', ''])
#                                     else:
#                                         # 有电损不通过
#                                         auditResult.auditStatus = '不通过'  # 返回稽核结果为不通过
#                                         audit_refused_type['信息与明细不符'] = 0
#                                         audit_list.append([str(bill_number), '用电量',
#                                                            '【' + str(data['es_number']) + '】' + str(
#                                                                electricity_consumption), str(n_1), '0', 'RPA',
#                                                            '用电量与电费明细不一致',
#                                                            AffixUtils.get_affix_url_with_name(affix_list_from_db,
#                                                                                               '附件2'), '4', ''])
#                         else:
#                             # 不包含电损
#                             bill_table_display_num_result = (
#                                         (float(bill_table_now_display_num) - float(bill_table_last_display_num)) * (
#                                             float(current_share_ratio) / 100))
#                             for sum, electricity_consumption_data in enumerate(electricity_consumption_list):
#                                 if sum >= 1 and float(electricity_consumption_data) == 0:
#                                     continue
#                                 if abs(bill_table_display_num_result - float(electricity_consumption_data)) > 1:
#                                     # 无电损不通过
#                                     auditResult.auditStatus = '不通过'  # 返回稽核结果为不通过
#                                     audit_refused_type['信息与明细不符'] = 0
#                                     audit_list.append([str(bill_number), '用电量',
#                                                        '【' + str(data['es_number']) + '】' + str(
#                                                            electricity_consumption_data),
#                                                        str(bill_table_display_num_result), '0', 'RPA',
#                                                        '用电量与电费明细不一致',
#                                                        AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'),
#                                                        '4', ''])
#                                 else:
#                                     audit_list.append([str(bill_number), '用电量',
#                                                        '【' + str(data['es_number']) + '】' + str(
#                                                            electricity_consumption_data),
#                                                        str(bill_table_display_num_result), '1', 'RPA',
#                                                        '合格',
#                                                        AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'),
#                                                        '4', ''])
#             except Exception as e:
#                 auditResult.auditStatus = '审核中'  # 返回稽核结果为转人工
#                 audit_list.append(
#                     [str(bill_number), '用电量', '【' + str(data['es_number']) + '】' + str(electricity_consumption), '',
#                      '0', 'RPA', 'RPA处理异常', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '4', ''])
#
#     return audit_list, auditResult,audit_refused_type

"""
    稽核规则九:【数据稽核】
        前提：本次分摊比例稽核正确：页面【电表缴费明细信息】-【电损电量（度）】与附件2（有单独列出电损电量）：页面【电表缴费明细信息】-【电损电量（度）】=【本次实际分摊比例】*附件2的【电损值】；
                #        如附件2中同时有总电量（包括电损）、上期读数和本期读数，则页面【电表缴费明细信息】-【电损电量（度）】=【本次实际分摊比例】*（附件2的【总电量】-附件2【本期读数-上期读数】）* 电表倍率。
                #        如果附件2（不符合上面情况或无单独列出电损电量）直接跳过。具体是那种情况，需在票据学习时区分附件2中电量是否包括电损。四舍五入匹配，相差±1度均可判断通过。
                # ----   不一致后动作：【审核状态】-【不通过】，备注：电损电量与电费明细不一致
"""
def audit_rule_nine(audit_list, auditResult, audit_refused_type, rar_file, result, whether_execute, bill_number,
                    now_display_num,bill_table_last_display_num,bill_table_total_power,es_magnification,
                    affix_list_from_db,
                    payment_detail_info_data, file_flag2, electricity_loss, ocr_electricity_loss,
                    current_share_ratio, bill_table_data_list):
    """
    :param payment_detail_info_data: 电表信息
    :param file_flag2: 附件2是否存在
    :param electricity_loss: 电损
    :param ocr_electricity_loss: 电损
    :param current_share_ratio:实际分摊比例
    :param bill_table_data_list: 识别的数据信息
    :return:
    """
    if whether_execute == False:
        try:
            if '附件2' in rar_file:
                audit_list.append(
                    [str(bill_number), '电损电量', str(electricity_loss), '', '0', 'RPA', '附件2文件格式不正确',
                     AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '5', ''])
            else:
                if not file_flag2:
                    audit_list.append(
                        [str(bill_number), '电损电量', str(electricity_loss), '', '0', 'RPA', '附件2电力明细清单不存在', '', '5', ''])
                else:
                    """
                    附件2中同时有总电量（包括电损）、上期读数和本期读数，
                    则页面【电表缴费明细信息】-【电损电量（度）】=【本次实际分摊比例】*（附件2的【总电量】-附件2【本期读数-上期读数】）* 电表倍率
                    """
                    if now_display_num and bill_table_last_display_num and bill_table_total_power:
                        if isinstance(electricity_loss, list):
                            electricity_loss = ''.join(electricity_loss)
                        co_electricity_loss = (float(current_share_ratio)/100)* \
                                              (float(bill_table_total_power) - (float(now_display_num) - float(bill_table_last_display_num))) \
                                              * float(es_magnification)
                        if electricity_loss == co_electricity_loss:
                            # audit_list.append([str(bill_number), '电损电量', str(co_electricity_loss),
                            #                    '0', '1', 'RPA', '合格',
                            #                    AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'),
                            #                    '4', ''])
                            audit_list.append(
                                [str(bill_number), '电损电量', str(electricity_loss), str(co_electricity_loss),
                                 '1',
                                 'RPA', '合格',
                                 AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '4', ''])
                        else:
                            auditResult.auditStatus = '审核中'  # 转人工
                            audit_list.append(
                                [str(bill_number), '电损电量', str(electricity_loss), '', '0', 'RPA',
                                 '附件2的【电损值】OCR识别为空',
                                 AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'),
                                 '4', ''])
                    else:
                        select_data_list = PyMysql().select_eleinfo('payment_detail_info', 'payment_code', bill_number)
                        if not ocr_electricity_loss:
                            for select_data in select_data_list[2]:
                                if float(select_data) != 0:
                                    auditResult.auditStatus = '审核中'  # 转人工
                                    audit_list.append(
                                        [str(bill_number), '电损电量', str(electricity_loss), '', '0', 'RPA',
                                         '附件2的【电损值】OCR识别为空',
                                         AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'),
                                         '4', ''])
                                else:
                                    audit_list.append([str(bill_number), '电损电量', str(select_data),
                                                       '0', '1', 'RPA', '合格',
                                                       AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'),
                                                       '4', ''])
                                    break

                        else:
                            for sum, select_data in enumerate(select_data_list[2]):
                                if sum >= 1 and float(select_data) == 0:
                                    continue
                                temp_els_loss = abs(float(select_data) - (float(current_share_ratio)/100) * float(
                                    ocr_electricity_loss) * es_magnification)
                                if temp_els_loss > 1:
                                    auditResult.auditStatus = '不通过'  # 返回稽核结果为不通过
                                    audit_refused_type['信息与明细不符'] = 0
                                    audit_list.append([str(bill_number), '电损电量', str(select_data),
                                                       str(temp_els_loss), '0', 'RPA',
                                                       '电损电量与电费明细不一致',
                                                       AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '4',
                                                       ''])
                                else:
                                    audit_list.append([str(bill_number), '电损电量', str(select_data),
                                                       str(temp_els_loss), '1', 'RPA', '合格',
                                                       AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'),
                                                       '4', ''])
        except Exception as e:
            # print(e)
            result['success'] = 1  # 返回稽核结果为转人工
            audit_list.append([str(bill_number), '电损电量', str(electricity_loss), '', '0', 'RPA', 'RPA处理异常',
                               AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '4', ''])
    else:
        for data in payment_detail_info_data:
            electricity_loss = data['electricity_loss']
            ocr_electricity_loss = ''
            ocr_total_power = ''
            ocr_last_display_num = ''
            ocr_now_display_num = ''
            current_share_ratio = data['current_share_ratio']  # 页面【电费缴费明细信息】-【本次实际分摊比例】
            es_magnification = data['es_magnification']
            current_share_ratio = re.findall(r"\d+\.?\d*", str(current_share_ratio).replace('%', ''))[0]
            for bill_table_data in bill_table_data_list:  # 通过户号识别结果列表找到对应的识别内容
                if str(bill_table_data[0]) == str(data['es_number']):
                    if bill_table_data[1] != '':
                        ocr_electricity_loss = bill_table_data[1]['ele_loss']  # OCR识别保存的电损
                        ocr_total_power = bill_table_data[1]['total_power']
                        ocr_last_display_num = bill_table_data[1]['last_display_num']
                        ocr_now_display_num = bill_table_data[1]['now_display_num']
            try:
                if '附件2' in rar_file:
                    audit_list.append(
                        [str(bill_number), '电损电量', '【' + str(data['es_number']) + '】' + str(electricity_loss), '', '0',
                         'RPA', '附件2文件格式不正确', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '5', ''])
                else:
                    if not file_flag2:
                        audit_list.append(
                            [str(bill_number), '电损电量', '【' + str(data['es_number']) + '】' + str(electricity_loss), '',
                             '0', 'RPA', '附件2电力明细清单不存在', '', '5', ''])
                    else:
                        if ocr_total_power and ocr_last_display_num and ocr_now_display_num:
                            co_electricity_loss = (float(current_share_ratio) / 100) * \
                                                  (float(ocr_total_power) - (float(ocr_now_display_num) - float(
                                                      ocr_last_display_num))) \
                                                  * float(es_magnification)
                            if electricity_loss == co_electricity_loss:
                                audit_list.append([str(bill_number), '电损电量', str(co_electricity_loss),
                                                   '0', '1', 'RPA', '合格',
                                                   AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'),
                                                   '4', ''])
                            else:
                                auditResult.auditStatus = '审核中'  # 转人工
                                audit_list.append(
                                    [str(bill_number), '电损电量', str(electricity_loss), '', '0', 'RPA',
                                     '附件2的【电损值】OCR识别为空',
                                     AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'),
                                     '4', ''])

                        else:
                            select_data_list = PyMysql().select_eleinfo('payment_detail_info', 'payment_code', bill_number)
                            if not ocr_electricity_loss:
                                for select_data in select_data_list[2]:
                                    if float(select_data) != 0:
                                        auditResult.auditStatus = '审核中'  # 转人工
                                        audit_list.append([str(bill_number), '电损电量',
                                                           '【' + str(data['es_number']) + '】' + str(electricity_loss), '',
                                                           '0', 'RPA', '附件2的【电损值】OCR识别为空',
                                                           AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'),
                                                           '4', ''])
                                    else:
                                        audit_list.append([str(bill_number), '电损电量',
                                                           '【' + str(data['es_number']) + '】' + str(
                                                               select_data), '0', '1', 'RPA', '合格',
                                                           AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'),
                                                           '4', ''])
                                        break
                            else:
                                select_data_list = PyMysql().select_eleinfo1(data)
                                for sum, select_data in enumerate(select_data_list[2]):
                                    if sum >= 1 and float(select_data) == 0:
                                        continue
                                    if abs(float(select_data) - (float(current_share_ratio)/100) * float(
                                            ocr_electricity_loss) * 0.01) > 1:
                                        auditResult.auditStatus = '不通过'  # 返回稽核结果为不通过
                                        audit_refused_type['信息与明细不符'] = 0
                                        audit_list.append([str(bill_number), '电损电量',
                                                           '【' + str(data['es_number']) + '】' + str(select_data),
                                                           str(float(str(current_share_ratio).replace('%', '')) * float(
                                                               ocr_electricity_loss) / 100), '0', 'RPA', '电损电量与电费明细不一致',
                                                           AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'),
                                                           '4', ''])
                                    else:
                                        audit_list.append([str(bill_number), '电损电量',
                                                           '【' + str(data['es_number']) + '】' + str(select_data),
                                                           str(float(str(current_share_ratio).replace('%', '')) * float(
                                                               ocr_electricity_loss) / 100), '1', 'RPA', '合格',
                                                           AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'),
                                                           '4', ''])
            except Exception as e:
                # print(e)
                result['success'] = 1  # 返回稽核结果为转人工
                audit_list.append(
                    [str(bill_number), '电损电量', '【' + str(data['es_number']) + '】' + str(electricity_loss), '', '0',
                     'RPA', 'RPA处理异常', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '4', ''])

    return audit_list, auditResult,audit_refused_type

"""
    稽核规则十:【数据稽核】
        页面【报账点缴费信息】的【缴费期始】和【缴费期终】=附件2根据页面【电表缴费明细信息】-【户号】查找对应的【时间】/【起止时间】，如果附件2没有时间字段不作比对
                # ----   不一致后动作：【审核状态】-【不通过】，备注：缴费期始/终与电费明细不一致
"""


def audit_rule_ten(auditResult, audit_list, whether_execute, rar_file, bill_number, affix_list_from_db,
                   audit_refused_type,
                   file_flag2, payment_detail_info_data, rp_payment_start_time, rp_payment_end_time,
                   bill_table_start_date, bill_table_end_date, bill_table_data_list):
    """
    :param file_flag2:
    :param payment_detail_info_data:
    :param rp_payment_start_time:
    :param rp_payment_end_time:
    :param bill_table_start_date:
    :param bill_table_end_date:
    :param bill_table_data_list:
    :return:
    """
    if whether_execute == False:
        try:
            if '附件2' in rar_file:
                audit_list.append(
                    [str(bill_number), '缴费期', str(rp_payment_start_time) + ',' + str(rp_payment_end_time), '', '0',
                     'RPA', '附件2文件格式不正确',
                     AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '5', ''])
            else:
                if not file_flag2:
                    audit_list.append(
                        [str(bill_number), '缴费期', str(rp_payment_start_time) + ',' + str(rp_payment_end_time), '', '0',
                         'RPA', '附件2电力明细清单不存在', '', '5', ''])
                else:
                    if rp_payment_start_time and bill_table_start_date and rp_payment_end_time and bill_table_end_date:
                        bill_table_end_date = bill_table_end_date.replace(' ', '')
                        bill_table_start_date = bill_table_start_date.replace(' ', '')
                        bill_table_end_date = bill_table_end_date.replace('/','-')
                        bill_table_start_date = bill_table_start_date.replace('/','-')
                        start_date = datetime.datetime.strptime(bill_table_start_date, "%Y-%m-%d")
                        end_date = datetime.datetime.strptime(bill_table_end_date, "%Y-%m-%d")
                        bill_table_start_date = str(start_date.strftime("%Y-%m-%d"))
                        bill_table_end_date = str(end_date.strftime("%Y-%m-%d"))
                        start_date = start_date + datetime.timedelta(days=1)
                        end_date = end_date - datetime.timedelta(days=1)
                        start_date = start_date.strftime("%Y-%m-%d")
                        end_date = end_date.strftime("%Y-%m-%d")
                        if (str(rp_payment_start_time) == str(bill_table_start_date)) and (
                                str(rp_payment_end_time) == str(bill_table_end_date)):
                            audit_list.append([str(bill_number), '缴费期',
                                               str(rp_payment_start_time) + ',' + str(rp_payment_end_time),
                                               str(bill_table_start_date) + ',' + str(bill_table_end_date), '1',
                                               'RPA', '合格',
                                               AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'),
                                               '1', ''])
                        elif (str(rp_payment_start_time) == str(bill_table_start_date)) and (
                                str(rp_payment_end_time) == str(end_date)):
                            audit_list.append([str(bill_number), '缴费期',
                                               str(rp_payment_start_time) + ',' + str(rp_payment_end_time),
                                               str(bill_table_start_date) + ',' + str(bill_table_end_date), '1',
                                               'RPA', '合格',
                                               AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'),
                                               '1', ''])
                        elif (str(rp_payment_start_time) == str(start_date)) and (
                                str(rp_payment_end_time) == str(bill_table_end_date)):
                            audit_list.append([str(bill_number), '缴费期',
                                               str(rp_payment_start_time) + ',' + str(rp_payment_end_time),
                                               str(bill_table_start_date) + ',' + str(bill_table_end_date), '1',
                                               'RPA', '合格',
                                               AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'),
                                               '1', ''])
                        else:
                            auditResult.auditStatus = '不通过'  # 返回稽核结果为不通过
                            audit_refused_type['信息与明细不符'] = 0
                            audit_list.append([str(bill_number), '缴费期',
                                               str(rp_payment_start_time) + ',' + str(rp_payment_end_time),
                                               str(bill_table_start_date) + ',' + str(bill_table_end_date),
                                               '0', 'RPA', '缴费期始/终与电费明细不一致',
                                               AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '1', ''])
                    else:
                        auditResult.auditStatus = '审核中'  # 转人工
                        audit_list.append(
                            [str(bill_number), '缴费期',
                             str(rp_payment_start_time) + ',' + str(rp_payment_end_time),
                             '', '0', 'RPA', '附件2起止时间为空', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'),
                             '1',
                             ''])
        except Exception as e:
            # print(e)
            auditResult.auditStatus = '审核中'  # 转人工
            audit_list.append(
                [str(bill_number), '缴费期', str(rp_payment_start_time) + ',' + str(rp_payment_end_time),
                 str(bill_table_start_date) + ',' + str(bill_table_end_date),
                 '0', 'RPA', 'RPA处理异常', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '1', ''])
    else:
        for data in payment_detail_info_data:
            try:
                if '附件2' in rar_file:
                    audit_list.append(
                        [str(bill_number), '缴费期',
                         '【' + str(data['es_number']) + '】' + str(rp_payment_start_time) + ',' + str(
                             rp_payment_end_time), '', '0', 'RPA',
                         '附件2文件格式不正确',
                         AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '5', ''])
                else:
                    if not file_flag2:
                        audit_list.append(
                            [str(bill_number), '缴费期',
                             '【' + str(data['es_number']) + '】' + str(rp_payment_start_time) + ',' + str(
                                 rp_payment_end_time), '', '0', 'RPA',
                             '附件2电力明细清单不存在', '', '5', ''])
                    else:
                        bill_table_start_date = ''
                        bill_table_end_date = ''
                        for bill_table_data in bill_table_data_list:  # 通过户号识别结果列表找到对应的识别内容
                            if str(bill_table_data[0]) == str(data['es_number']):
                                if bill_table_data[1] != '':
                                    bill_table_start_date = bill_table_data[1]['start_date']  # 读数开始日期
                                    bill_table_end_date = bill_table_data[1]['end_date']  # 读数开始日期
                        if rp_payment_start_time and bill_table_start_date != '' and rp_payment_end_time and bill_table_end_date != '':
                            bill_table_end_date = bill_table_end_date.replace(' ', '')
                            bill_table_start_date = bill_table_start_date.replace(' ', '')
                            start_date = datetime.datetime.strptime(bill_table_start_date, "%Y-%m-%d")
                            end_date = datetime.datetime.strptime(bill_table_end_date, "%Y-%m-%d")
                            bill_table_start_date = str(start_date.strftime("%Y-%m-%d"))
                            bill_table_end_date = str(end_date.strftime("%Y-%m-%d"))
                            start_date = start_date + datetime.timedelta(days=1)
                            end_date = end_date - datetime.timedelta(days=1)
                            start_date = start_date.strftime("%Y-%m-%d")
                            end_date = end_date.strftime("%Y-%m-%d")
                            if (str(rp_payment_start_time) == str(bill_table_start_date)) and (
                                    str(rp_payment_end_time) == str(bill_table_end_date)):
                                audit_list.append([str(bill_number), '缴费期',
                                                   '【' + str(data['es_number']) + '】' + str(
                                                       rp_payment_start_time) + ',' + str(
                                                       rp_payment_end_time),
                                                   str(bill_table_start_date) + ',' + str(
                                                       bill_table_end_date), '1',
                                                   'RPA', '合格',
                                                   AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'),
                                                   '1', ''])
                            elif (str(rp_payment_start_time) == str(bill_table_start_date)) and (
                                    str(rp_payment_end_time) == str(end_date)):
                                audit_list.append([str(bill_number), '缴费期',
                                                   '【' + str(data['es_number']) + '】' + str(
                                                       rp_payment_start_time) + ',' + str(
                                                       rp_payment_end_time),
                                                   str(bill_table_start_date) + ',' + str(
                                                       bill_table_end_date), '1',
                                                   'RPA', '合格',
                                                   AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'),
                                                   '1', ''])
                            elif (str(rp_payment_start_time) == str(start_date)) and (
                                    str(rp_payment_end_time) == str(bill_table_end_date)):
                                audit_list.append([str(bill_number), '缴费期',
                                                   '【' + str(data['es_number']) + '】' + str(
                                                       rp_payment_start_time) + ',' + str(
                                                       rp_payment_end_time),
                                                   str(bill_table_start_date) + ',' + str(
                                                       bill_table_end_date), '1',
                                                   'RPA', '合格',
                                                   AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'),
                                                   '1', ''])
                            else:
                                auditResult.auditStatus = '不通过'  # 返回稽核结果为不通过
                                audit_refused_type['信息与明细不符'] = 0
                                audit_list.append([str(bill_number), '缴费期',
                                                   '【' + str(data['es_number']) + '】' + str(
                                                       rp_payment_start_time) + ',' + str(
                                                       rp_payment_end_time),
                                                   str(bill_table_start_date) + ',' + str(
                                                       bill_table_end_date),
                                                   '0', 'RPA', '缴费期始/终与电费明细不一致',
                                                   AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '1',
                                                   ''])
                        else:
                            auditResult.auditStatus = '审核中'  # 转人工
                            audit_list.append(
                                [str(bill_number), '缴费期',
                                 '【' + str(data['es_number']) + '】' + str(rp_payment_start_time) + ',' + str(
                                     rp_payment_end_time),
                                 '', '0', 'RPA', '附件2起止时间为空',
                                 AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'),
                                 '1',
                                 ''])
            except Exception as e:
                # print(e)
                auditResult.auditStatus = '审核中'  # 转人工
                audit_list.append(
                    [str(bill_number), '缴费期',
                     '【' + str(data['es_number']) + '】' + str(rp_payment_start_time) + ',' + str(rp_payment_end_time),
                     str(bill_table_start_date) + ',' + str(bill_table_end_date),
                     '0', 'RPA', 'RPA处理异常', AffixUtils.get_affix_url_with_name(affix_list_from_db, '附件2'), '1', ''])

    return audit_list, auditResult,audit_refused_type


